#! /usr/bin/python3
import torch
import os
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt

# prepare the data and dataloader
train_data = datasets.FashionMNIST(
        root = "../datasets",
        train = True,
        download = True,
        transform = ToTensor())

test_data = datasets.FashionMNIST(
        root = "../datasets",
        train = False,
        download = True,
        transform = ToTensor())


batch_size = 64
train_dataloader = DataLoader(train_data, batch_size = batch_size)
test_dataloader = DataLoader(test_data, batch_size = batch_size)

for X, y in train_dataloader:
    print("shape of X [N, C, H, W]: ", X.shape)
    print("shape of y: ", y.shape, y.dtype)
    break


# create model
device = 'cuda'
class LeNet(nn.Module):
    def __init__(self):
        super(LeNet, self).__init__()
        self.flatten = nn.Flatten()
        self.line1 = nn.Linear(28*28, 512)
        self.relu1 = nn.ReLU()
        self.line2 = nn.Linear(512, 512)
        self.relu2 = nn.ReLU()
        self.line3 = nn.Linear(512, 10)
        self.relu3 = nn.ReLU()
        

    def forward(self, x):
        x = self.flatten(x)
        x = self.line1(x)
        x = self.relu1(x)
        x = self.line2(x)
        x = self.relu2(x)
        x = self.line3(x)
        x = self.relu3(x)
        return x

model = LeNet().to(device)
print(model)



# train
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)

def train(dataloader, model , loss_fn, optimizer):
    size = len(dataloader.dataset)

    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device), y.to(device)

        #compute the prediction loss
        pred = model(X)
        loss = loss_fn(pred, y)

        # backpropagation
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if batch%100 == 0:
            loss, current = loss.item(), batch * len(X)
            print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
    pass


def test(dataloader, model):
    size = len(dataloader.dataset)
    model.eval()
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
            correct += (pred.argmax(1) == y).type(torch.float).sum().item()
    test_loss /= size
    correct /= size
    print(f"Test Erroe:\n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f}\n")
    pass

epochs = 20

if os.path.exists("lenet.pt"):
    model.load_state_dict(torch.load("lenet.pt"))

for t in range(epochs):
    print(f"Epoch {t+1}\n ----------------------------")
    train(train_dataloader, model, loss_fn, optimizer)
    test(test_dataloader, model)
print("Done")

# save the weights/model
torch.save(model.state_dict(), "lenet.pt")
print("model saved in lenet.pt")
